<template>
  <el-drawer
    v-model="visible"
    title="批量操作"
    direction="rtl"
    size="500px"
    @close="handleClose"
    class="batch-operations-drawer"
  >
    <div class="batch-operations" v-loading="loading">
      <el-alert
        :title="`已选择 ${selectedCustomers.length} 个客户`"
        type="info"
        show-icon
        class="selection-info"
      />
      
      <div class="operation-options">
        <el-card shadow="never" class="operation-card">
          <template #header>
            <div class="card-header">
              <el-icon><User /></el-icon>
              <span>客户等级操作</span>
            </div>
          </template>
          
          <div class="operation-content">
            <el-form :model="levelForm" label-width="100px">
              <el-form-item label="批量设置等级">
                <el-select v-model="levelForm.level" placeholder="请选择客户等级" style="width: 100%">
                  <el-option label="VIP客户" value="vip" />
                  <el-option label="重要客户" value="important" />
                  <el-option label="普通客户" value="normal" />
                  <el-option label="潜在客户" value="potential" />
                </el-select>
              </el-form-item>
              
              <el-form-item>
                <el-button 
                  type="primary" 
                  @click="handleBatchSetLevel"
                  :disabled="!levelForm.level"
                  class="operation-btn"
                >
                  批量设置等级
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
        
        <el-card shadow="never" class="operation-card">
          <template #header>
            <div class="card-header">
              <el-icon><TrendCharts /></el-icon>
              <span>客户状态操作</span>
            </div>
          </template>
          
          <div class="operation-content">
            <el-form :model="statusForm" label-width="100px">
              <el-form-item label="批量设置状态">
                <el-select v-model="statusForm.status" placeholder="请选择客户状态" style="width: 100%">
                  <el-option label="合作中" value="active" />
                  <el-option label="暂停合作" value="suspended" />
                  <el-option label="已终止" value="terminated" />
                  <el-option label="风险客户" value="risk" />
                </el-select>
              </el-form-item>
              
              <el-form-item>
                <el-button 
                  type="primary" 
                  @click="handleBatchSetStatus"
                  :disabled="!statusForm.status"
                  class="operation-btn"
                >
                  批量设置状态
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
        
        <el-card shadow="never" class="operation-card">
          <template #header>
            <div class="card-header">
              <el-icon><Star /></el-icon>
              <span>客户评分操作</span>
            </div>
          </template>
          
          <div class="operation-content">
            <el-form :model="ratingForm" label-width="100px">
              <el-form-item label="批量设置评分">
                <el-rate
                  v-model="ratingForm.customerValue"
                  :max="5"
                  allow-half
                  style="margin-top: 8px;"
                />
              </el-form-item>
              
              <el-form-item>
                <el-button 
                  type="primary" 
                  @click="handleBatchSetRating"
                  :disabled="ratingForm.customerValue === 0"
                  class="operation-btn"
                >
                  批量设置评分
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
        
        <el-card shadow="never" class="operation-card">
          <template #header>
            <div class="card-header">
              <el-icon><User /></el-icon>
              <span>负责销售操作</span>
            </div>
          </template>
          
          <div class="operation-content">
            <el-form :model="salesmanForm" label-width="100px">
              <el-form-item label="批量设置销售">
                <el-select 
                  v-model="salesmanForm.salesman" 
                  placeholder="请选择负责销售" 
                  style="width: 100%"
                  filterable
                  clearable
                >
                  <el-option 
                    v-for="salesman in salesmen" 
                    :key="salesman.id" 
                    :label="salesman.name" 
                    :value="salesman.name" 
                  />
                </el-select>
              </el-form-item>
              
              <el-form-item>
                <el-button 
                  type="primary" 
                  @click="handleBatchSetSalesman"
                  :disabled="!salesmanForm.salesman"
                  class="operation-btn"
                >
                  批量设置销售
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
        
        <el-card shadow="never" class="operation-card danger">
          <template #header>
            <div class="card-header">
              <el-icon><Delete /></el-icon>
              <span>危险操作</span>
            </div>
          </template>
          
          <div class="operation-content">
            <el-button 
              type="danger" 
              @click="handleBatchDelete"
              class="danger-btn"
              :disabled="selectedCustomers.length === 0"
            >
              批量删除客户
            </el-button>
          </div>
        </el-card>
      </div>
    </div>
    
    <template #footer>
      <div class="drawer-footer">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  User, TrendCharts, Star, Delete 
} from '@element-plus/icons-vue'
import { customerAPI } from '@/api/customer'
import { systemAPI } from '@/api/system'

interface Customer {
  id: string
  name: string
  level: string
  status: string
  customerValue: number
  [key: string]: any
}

const props = defineProps<{
  modelValue: boolean
  selectedCustomers: Customer[]
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'batch-set-level', level: string): void
  (e: 'batch-set-status', status: string): void
  (e: 'batch-set-rating', rating: number): void
  (e: 'batch-set-salesman', salesman: string): void
  (e: 'batch-delete'): void
  (e: 'close'): void
}>()

const visible = ref(false)
const loading = ref(false)
const salesmen = ref<any[]>([])

// 表单数据
const levelForm = ref({
  level: ''
})

const statusForm = ref({
  status: ''
})

const ratingForm = ref({
  customerValue: 0
})

const salesmanForm = ref({
  salesman: ''
})

// 监听modelValue变化
watch(() => props.modelValue, (newValue: boolean) => {
  visible.value = newValue
})

// 监听visible变化
watch(visible, (newValue: boolean) => {
  emit('update:modelValue', newValue)
})

// 获取销售人员列表
const loadSalesmen = async () => {
  try {
    const response: any = await systemAPI.getSalesmen()
    salesmen.value = response.data.list || []
  } catch (error) {
    console.error('获取销售人员列表失败:', error)
    // 如果API调用失败，使用默认数据
    salesmen.value = [
      { name: '张三', id: 1 },
      { name: '李四', id: 2 },
      { name: '王五', id: 3 },
      { name: '赵六', id: 4 }
    ]
  }
}

// 方法
const handleClose = () => {
  emit('close')
  visible.value = false
}

const handleBatchSetLevel = async () => {
  if (!levelForm.value.level) {
    ElMessage.warning('请选择客户等级')
    return
  }
  
  try {
    loading.value = true
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    emit('batch-set-level', levelForm.value.level)
    ElMessage.success(`成功为 ${props.selectedCustomers.length} 个客户设置等级`)
    levelForm.value.level = ''
  } catch (error) {
    ElMessage.error('批量设置等级失败')
  } finally {
    loading.value = false
  }
}

const handleBatchSetStatus = async () => {
  if (!statusForm.value.status) {
    ElMessage.warning('请选择客户状态')
    return
  }
  
  try {
    loading.value = true
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    emit('batch-set-status', statusForm.value.status)
    ElMessage.success(`成功为 ${props.selectedCustomers.length} 个客户设置状态`)
    statusForm.value.status = ''
  } catch (error) {
    ElMessage.error('批量设置状态失败')
  } finally {
    loading.value = false
  }
}

const handleBatchSetRating = async () => {
  if (ratingForm.value.customerValue === 0) {
    ElMessage.warning('请设置客户评分')
    return
  }
  
  try {
    loading.value = true
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    emit('batch-set-rating', ratingForm.value.customerValue)
    ElMessage.success(`成功为 ${props.selectedCustomers.length} 个客户设置评分`)
    ratingForm.value.customerValue = 0
  } catch (error) {
    ElMessage.error('批量设置评分失败')
  } finally {
    loading.value = false
  }
}

const handleBatchSetSalesman = async () => {
  if (!salesmanForm.value.salesman) {
    ElMessage.warning('请选择负责销售')
    return
  }
  
  try {
    loading.value = true
    // 调用真实的API
    const customerIds = props.selectedCustomers.map((customer: Customer) => customer.id)
    await customerAPI.batchSetResponsibleSalesman(customerIds, salesmanForm.value.salesman)
    emit('batch-set-salesman', salesmanForm.value.salesman)
    ElMessage.success(`成功为 ${props.selectedCustomers.length} 个客户设置负责销售`)
    salesmanForm.value.salesman = ''
  } catch (error) {
    ElMessage.error('批量设置负责销售失败: ' + (error as Error).message)
  } finally {
    loading.value = false
  }
}

const handleBatchDelete = async () => {
  if (props.selectedCustomers.length === 0) {
    ElMessage.warning('请选择要删除的客户')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${props.selectedCustomers.length} 个客户吗？此操作不可恢复！`,
      '批量删除确认',
      {
        type: 'warning',
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        confirmButtonClass: 'el-button--danger'
      }
    )
    
    loading.value = true
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 800))
    emit('batch-delete')
    ElMessage.success(`成功删除 ${props.selectedCustomers.length} 个客户`)
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  } finally {
    loading.value = false
  }
}

// 生命周期
onMounted(() => {
  loadSalesmen()
})
</script>

<style scoped>
.batch-operations-drawer {
  border-radius: 8px;
  overflow: hidden;
}

.batch-operations {
  height: calc(100% - 60px);
  display: flex;
  flex-direction: column;
}

.selection-info {
  margin-bottom: 20px;
}

.operation-options {
  flex: 1;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.operation-card {
  transition: all 0.3s ease;
}

.operation-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.operation-card.danger {
  border-color: #f56c6c;
}

.operation-card.danger:hover {
  box-shadow: 0 4px 12px rgba(245, 108, 108, 0.2);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
}

.operation-content {
  padding: 16px 0;
}

.operation-btn,
.danger-btn {
  width: 100%;
  transition: all 0.3s ease;
}

.operation-btn:hover,
.danger-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.danger-btn {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

.danger-btn:hover {
  background-color: #ff4d4f;
  border-color: #ff4d4f;
  box-shadow: 0 4px 8px rgba(245, 108, 108, 0.3);
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 12px 20px;
  border-top: 1px solid #ebeef5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .batch-operations-drawer {
    width: 95% !important;
  }
}
</style>